import { getCurrentTimeParam } from "./globalTimeFilter.js";
import { API_CONFIG } from "./config.js";

document.addEventListener("DOMContentLoaded", function () {
  // 获取业务类别统计容器
  const cjpieElement = document.getElementById("CJpie");
  if (!cjpieElement) return;

  // 创建新的业务类别统计结构
  cjpieElement.innerHTML = `
        <div class="business-category-container">
            <div id="business-category-chart"></div>
        </div>
    `;

  // 添加样式
  const style = document.createElement("style");
  style.innerHTML = `
        .business-category-container {
            height: 100%;
            width: 100%;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: flex-end;
        }       
        #business-category-chart {
            width: 100%;
            height: 100%;
            position: relative;
            border-radius: 8px;
            border: 1px solid rgba(36, 187, 236, 0.2);
            box-shadow: 0 8px 32px rgba(2, 20, 42, 0.5);
            box-sizing: border-box;
        }
        
        .business-category-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid rgba(36, 187, 236, 0.3);
        }
        
        .business-category-title h3 {
            font-size: 1.4rem;
            font-weight: 600;
            color: #24bbec;
            position: relative;
            margin: 0;
        }
        
        .business-category-title h3::before {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 0;
            width: 100%;
            height: 3px;
            border-radius: 3px;
        }
        
        .update-time {
            font-size: 1.3rem;
            color: #a2d3e8;
        }
    `;
  document.head.appendChild(style);

  // 初始化图表
  initBusinessCategoryChart();
});

function initBusinessCategoryChart() {
  const chartDom = document.getElementById("business-category-chart");
  if (!chartDom) return;

  const chart = echarts.init(chartDom);

  // 在函数内部声明变量
  let sortedCategories = [];
  let sortedData = [];
  let start = 0;
  const visibleItems = 10;
  const interval = 5000;

  // 监听时间变化事件
  document.addEventListener("timePeriodChanged", function (event) {
    fetchDataAndUpdate();
  });

  function fetchDataAndUpdate() {
    let timeParam = getCurrentTimeParam();


    const id = "gfwqsdfaca044c1b0dbb1desswrh5tjyt";
    const type = "1";

    // 使用普通对象而不是URLSearchParams
    const params = {
      id: id,
      time: timeParam,
      type: type,
    };

    // 修正URL路径 - 添加/api
    const url = `${API_CONFIG.BASE_URL}/api/metrics/${id}/single-metrics-value`;

    console.log("发送请求到:", url, "参数:", params); // 调试用

    axios
      .get(url, { params })
      .then((response) => {
        console.log("获取到的业务类别数据:", response.data.data); // 调试用

        if (response.data && response.data.code === "00000") {
          const result = response.data.data;
          // 处理数据，提取业务类别和数量
          const categories = [];
          const data = [];

          // 假设每个数据项代表一个业务类别
          // 实际应根据接口返回的数据结构调整
          result.forEach((item) => {
            categories.push(item.fis_category);
            data.push(parseInt(item.fis_category_work_order_count));
          });

          updateChart(categories, data);
          updateUpdateTime();
        } else {
          console.error(
            "获取业务类别数据失败:",
            response.data ? response.data.msg : "未知错误"
          );
        }
      })
      .catch((error) => {
        console.error("获取业务类别数据失败:", error);
      });
  }

  // 图表配置 - 改为折线图
  function updateChart(categories, data) {
    // 按数量从高到低排序
    const sortedIndices = data
        .map((val, idx) => ({ val, idx }))
        .sort((a, b) => b.val - a.val)
        .map((item) => item.idx);

    // 直接赋值给外部变量（不要用 const 重新声明）
    sortedCategories = sortedIndices.map((idx) => categories[idx]);
    sortedData = sortedIndices.map((idx) => data[idx]);

    const option = {
      tooltip: {
        trigger: "axis",
        backgroundColor: "rgba(6, 33, 68, 0.9)",
        borderColor: "#24bbec",
        textStyle: {
          color: "#fff",
          fontSize: 20,
        },
        formatter: function (params) {
          const data = params[0];
          return `${data.name}<br/>工单数量: <b>${data.value}</b>`;
        },
      },
      grid: {
        left: "3%",
        right: "5%",
        bottom: "5%", // 增加底部空间用于显示类别标签
        top: "20%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: sortedCategories,
        axisLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.5)",
          },
        },
        axisLabel: {
          color: "#a2d3e8",
          fontSize: 16,
          rotate: 30, // 旋转标签避免重叠
          interval: 0, // 显示所有标签
          formatter: function (value) {
            return value.length > 8 ? value.substring(0, 8) + "..." : value;
          },
        },
        axisTick: {
          alignWithLabel: true,
        },
        name: "业务类别",
        nameLocation: "end",
        nameTextStyle: {
          color: "#a2d3e8",
          fontSize: 16,
          padding: [10, 0, 0, 0],
        },
      },
      yAxis: {
        type: "value",
        name: "工单数量",
        nameTextStyle: {
          color: "#a2d3e8",
          fontSize: 16,
          padding: [0, 0, 20, 0],
        },
        axisLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.5)",
          },
        },
        axisLabel: {
          color: "#a2d3e8",
          fontSize: 16,
        },
        splitLine: {
          lineStyle: {
            color: "rgba(162, 211, 232, 0.1)",
          },
        },
      },
      series: [
        {
          name: "工单数量",
          type: "line",
          data: sortedData,
          smooth: true, // 平滑曲线
          symbol: "circle", // 数据点形状
          symbolSize: 10, // 数据点大小
          lineStyle: {
            width: 3, // 线条宽度
            color: "#24bbec", // 线条颜色
          },
          itemStyle: {
            color: "#24bbec", // 数据点颜色
            borderColor: "#fff",
            borderWidth: 2,
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "rgba(36, 187, 236, 0.5)" },
              { offset: 1, color: "rgba(36, 187, 236, 0.1)" },
            ]),
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: "rgba(36, 187, 236, 0.5)",
            },
            lineStyle: {
              width: 4,
              color: "#ffc640",
            }
          },
          label: {
            show: true,
            position: "top",
            formatter: "{c}",
            color: "#fff",
            fontSize: 16,
            backgroundColor: "rgba(6, 33, 68, 0.7)",
            padding: [5, 8],
            borderRadius: 4,
          },
        },
      ],
      dataZoom: [
        {
          type: "inside",
          xAxisIndex: 0, // 改为作用于x轴
          zoomLock: false,
          minValueSpan: visibleItems,
          maxValueSpan: visibleItems,
          start: 0,
          end: 100,
        },
      ],
      animation: true,
      animationDuration: 1000,
      animationEasing: "cubicInOut",
    };

    chart.setOption(option);
  }

  // 更新更新时间
  function updateUpdateTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, "0");
    const minutes = now.getMinutes().toString().padStart(2, "0");
    const seconds = now.getSeconds().toString().padStart(2, "0");

    const updateTimeElement = document.getElementById("business-update-time");
    if (updateTimeElement) {
      updateTimeElement.textContent = `${hours}:${minutes}:${seconds}`;
    }
  }

  // 自动滚动功能 - 调整为折线图的自动滚动
  function autoScroll() {
    if (sortedCategories.length === 0) return;

    start = (start + 1) % (sortedCategories.length - visibleItems + 1);
    chart.dispatchAction({
      type: "dataZoom",
      startValue: start,
      endValue: start + visibleItems,
      xAxisIndex: 0 // 改为作用于x轴
    });
  }

  // 初始加载
  fetchDataAndUpdate();

  // 每10秒更新一次数据
  setInterval(fetchDataAndUpdate, 10000000);

  let scrollInterval = setInterval(autoScroll, interval);

  // 处理窗口大小变化
  window.addEventListener("resize", function () {
    chart.resize();
  });

  // 鼠标悬停时暂停滚动
  chartDom.addEventListener("mouseover", () => {
    clearInterval(scrollInterval);
  });

  chartDom.addEventListener("mouseout", () => {
    scrollInterval = setInterval(autoScroll, interval);
  });
}
